package org.rjxh.examfront.filter;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import org.rjxh.examfront.pojo.LoginUser;
import org.rjxh.examfront.pojo.R;
import org.rjxh.examfront.web.tools.JwtUtils;
import org.rjxh.examfront.web.tools.RedisCache;
import org.rjxh.examfront.web.tools.WebUtils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class TokenAuthenticatorFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");

        if (StringUtil.isNullOrEmpty(token)) {
            //没有token直接放行，同时也没有个人信息
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //有token
        String userId;
        try {
            Claims claims = jwtUtils.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            WebUtils.renderString(httpServletResponse, JSON.toJSONString( new R(401, "token无效")));
            return;
        }

        String redisKey = "login:" + userId;
        LoginUser cacheObject = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(cacheObject)) {
            WebUtils.renderString(httpServletResponse, JSON.toJSONString( new R(401, "登录超时")));
            return;
        }

        // 刷新redis的过期时间
        redisCache.expire(redisKey, 60, TimeUnit.MINUTES);

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(cacheObject, null,cacheObject.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(httpServletRequest, httpServletResponse);


    }
}
